/**
 * 操作日志查询页面JavaScript模块
 *
 * 功能特性：
 * - 日志列表查询和分页
 * - 多维度筛选和搜索
 * - 操作统计展示
 * - 日志详情查看
 * - 链路追踪支持
 *
 * @author SongRenShuo
 * @version 1.0.0
 * @since 2025-08-29
 */

// 使用全局API服务（从 api.js 中获取）
// 确保 api.js 已经加载
function getLocalApiInstance() {
    // 直接使用全局api实例
    if (window.api && typeof window.api.getOperationLogStatistics === 'function') {
        return window.api;
    }

    // 尝试使用全局API实例获取方法
    if (window.getApiInstance && typeof window.getApiInstance === 'function') {
        const apiInstance = window.getApiInstance();
        if (apiInstance && typeof apiInstance.getOperationLogStatistics === 'function') {
            return apiInstance;
        }
    }

    console.warn('⚠️ 无法获取API实例，请确保 api.js 已加载');
    return null;
}

// 带重试机制的API实例获取
async function getApiInstanceWithRetry() {
    return new Promise((resolve) => {
        let retries = 0;
        const maxRetries = 10;
        const delay = 200; // 增加延迟时间

        const tryGetApi = () => {
            const apiInstance = getLocalApiInstance();
            if (apiInstance) {
                console.log('✅ API实例获取成功');
                resolve(apiInstance);
                return;
            }

            if (retries < maxRetries) {
                retries++;
                console.log(`🔄 等待API实例加载... ${retries}/${maxRetries}`);
                setTimeout(tryGetApi, delay);
            } else {
                console.error('❌ API实例加载超时');
                resolve(null);
            }
        };

        tryGetApi();
    });
}

class OperationLogManager {
    constructor() {
        this.currentPage = 1;
        this.pageSize = 10;
        this.currentSearchParams = {};
        this.isInitialized = false;

        this.init();
    }

    /**
     * 初始化页面
     */
    async init() {
        console.log('🚀 操作日志管理器开始初始化...');

        this.bindEvents();

        // 等待API准备就绪再加载数据
        try {
            const api = await getApiInstanceWithRetry();
            if (api) {
                console.log('✅ API实例获取成功，开始加载数据');
                await this.loadStatistics();
                await this.loadLogList();
                this.isInitialized = true;
            } else {
                console.warn('⚠️ API实例不可用，跳过数据加载');
                this.showInitError();
            }
        } catch (error) {
            console.error('❌ API初始化失败:', error);
            this.showInitError();
        }

        console.log('✅ 操作日志查询页面初始化完成');
    }

    /**
     * 显示初始化错误
     */
    showInitError() {
        this.showStatisticsError('API服务不可用');
        this.showError('API服务不可用，请检查后端服务是否启动');
    }

    /**
     * 绑定事件监听器
     */
    bindEvents() {
        // 搜索表单提交
        document.getElementById('searchForm').addEventListener('submit', (e) => {
            e.preventDefault();
            this.handleSearch();
        });

        // 点击弹窗外部关闭
        document.getElementById('detailModal').addEventListener('click', (e) => {
            if (e.target.id === 'detailModal') {
                this.closeModal();
            }
        });
    }

    /**
     * 处理搜索
     */
    handleSearch() {
        this.currentPage = 1;
        this.currentSearchParams = this.getSearchParams();
        this.loadLogList();
    }

    /**
     * 获取搜索参数
     */
    getSearchParams() {
        return {
            moduleType: document.getElementById('moduleType').value,
            operationType: document.getElementById('operationType').value,
            operator: document.getElementById('operator').value.trim(),
            status: document.getElementById('status').value,
            businessName: document.getElementById('businessName').value.trim(),
            traceId: document.getElementById('traceId').value.trim()
        };
    }

    /**
     * 重置表单
     */
    resetForm() {
        document.getElementById('searchForm').reset();
        this.currentPage = 1;
        this.currentSearchParams = {};
        this.loadLogList();
    }

    /**
     * 加载统计信息
     */
    async loadStatistics() {
        try {
            const api = await getApiInstanceWithRetry();
            if (!api) {
                throw new Error('API服务不可用');
            }

            // 使用api.js中的方法加载详细统计信息
            const detailedResult = await api.getOperationLogStatistics();
            if (detailedResult.code === 0 && detailedResult.data) {
                this.updateDetailedStatistics(detailedResult.data);
            } else {
                throw new Error(detailedResult.msg || '获取统计信息失败');
            }
        } catch (error) {
            console.error('加载统计信息失败:', error);
            this.showStatisticsError('加载统计信息失败');
        }
    }

    /**
     * 更新详细统计显示
     */
    updateDetailedStatistics(stats) {
        document.getElementById('todayCount').textContent = this.formatNumber(stats.todayCount || 0);
        document.getElementById('successCount').textContent = this.formatNumber(stats.successCount || 0);
        document.getElementById('errorCount').textContent = this.formatNumber(stats.errorCount || 0);
        document.getElementById('totalCount').textContent = this.formatNumber(stats.totalCount || 0);
    }

    /**
     * 显示统计错误
     */
    showStatisticsError(message) {
        document.getElementById('todayCount').textContent = '-';
        document.getElementById('successCount').textContent = '-';
        document.getElementById('errorCount').textContent = '-';
        document.getElementById('totalCount').textContent = '-';
        console.error(message);
    }

    /**
     * 格式化数字显示
     */
    formatNumber(num) {
        if (num >= 1000000) {
            return (num / 1000000).toFixed(1) + 'M';
        } else if (num >= 1000) {
            return (num / 1000).toFixed(1) + 'K';
        }
        return num.toString();
    }

    /**
     * 加载日志列表
     */
    async loadLogList() {
        try {
            this.showLoading();

            const api = await getApiInstanceWithRetry();
            if (!api) {
                throw new Error('API服务不可用');
            }

            const requestBody = {
                ...this.currentSearchParams,
                currentPage: this.currentPage,
                pageSize: this.pageSize
            };

            // 移除空值参数
            Object.keys(requestBody).forEach(key => {
                if (requestBody[key] === '' || requestBody[key] === null || requestBody[key] === undefined) {
                    delete requestBody[key];
                }
            });

            // 使用api.js中的方法
            const result = await api.getOperationLogList(requestBody);

            if (result.code === 0) {
                this.renderLogList(result.data);
            } else {
                throw new Error(result.msg || '查询失败');
            }
        } catch (error) {
            console.error('加载日志列表失败:', error);
            this.showError('加载日志列表失败: ' + error.message);
        }
    }

    /**
     * 显示加载状态
     */
    showLoading() {
        const tbody = document.getElementById('logTableBody');
        tbody.innerHTML = `
            <tr>
                <td colspan="8" class="loading">
                    <div>正在加载日志数据...</div>
                </td>
            </tr>
        `;
    }

    /**
     * 显示错误信息
     */
    showError(message) {
        const tbody = document.getElementById('logTableBody');
        tbody.innerHTML = `
            <tr>
                <td colspan="8" class="empty-state">
                    <div style="color: #e74c3c;">❌ ${message}</div>
                </td>
            </tr>
        `;
    }

    /**
     * 渲染日志列表
     */
    renderLogList(pageData) {
        const tbody = document.getElementById('logTableBody');

        if (!pageData || !pageData.list || pageData.list.length === 0) {
            tbody.innerHTML = `
                <tr>
                    <td colspan="8" class="empty-state">
                        <div>📝 暂无日志数据</div>
                        <div style="font-size: 14px; margin-top: 5px;">尝试调整搜索条件或稍后再试</div>
                    </td>
                </tr>
            `;
            return;
        }

        const rows = pageData.list.map(log => `
            <tr>
                <td>${this.formatDateTime(log.operationTime)}</td>
                <td>${this.formatModuleType(log.moduleType)}</td>
                <td>${this.formatOperationType(log.operationType)}</td>
                <td title="${log.operationDescription || '-'}">${this.truncateText(log.operationDescription || '-', 20)}</td>
                <td>${log.operator || '-'}</td>
                <td>${this.formatExecutionTime(log.executionTime)}</td>
                <td>${this.formatStatus(log.status)}</td>
                <td>
                    <button class="btn btn-primary" onclick="operationLogManager.showDetail(${log.id})" style="padding: 4px 8px; font-size: 12px;">
                        详情
                    </button>
                </td>
            </tr>
        `).join('');

        tbody.innerHTML = rows;
        this.renderPagination(pageData);
    }

    /**
     * 格式化日期时间
     */
    formatDateTime(dateTime) {
        if (!dateTime) return '-';
        const date = new Date(dateTime);
        return date.toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit'
        });
    }

    /**
     * 格式化模块类型
     */
    formatModuleType(moduleType) {
        const moduleTypeMap = {
            'AREA': '区域管理',
            'FREIGHT_STRATEGY': '运费策略',
            'AREA_PRICING': '区域定价',
            'WEIGHT_SEGMENT_RULE': '重量区间规则',
            'STRATEGY_ASSIGNMENT': '策略分配',
            'PRICING_AREA_MAPPING': '定价区域映射',
            'UNIFIED_CONFIG': '统一配置'
        };
        return moduleTypeMap[moduleType] || moduleType;
    }

    /**
     * 格式化操作类型
     */
    formatOperationType(operationType) {
        const typeMap = {
            'INSERT': { text: '新增', class: 'op-insert' },
            'UPDATE': { text: '修改', class: 'op-update' },
            'DELETE': { text: '删除', class: 'op-delete' },
            'BATCH_INSERT': { text: '批量新增', class: 'op-batch' },
            'BATCH_UPDATE': { text: '批量修改', class: 'op-batch' },
            'BATCH_DELETE': { text: '批量删除', class: 'op-batch' }
        };

        const type = typeMap[operationType] || { text: operationType, class: 'op-insert' };
        return `<span class="operation-type ${type.class}">${type.text}</span>`;
    }

    /**
     * 格式化状态
     */
    formatStatus(status) {
        if (status === 1) {
            return '<span class="status-badge status-success">成功</span>';
        } else if (status === 2) {
            return '<span class="status-badge status-error">失败</span>';
        }
        return '<span class="status-badge">未知</span>';
    }

    /**
     * 格式化执行时间
     */
    formatExecutionTime(time) {
        if (time == null || time == undefined) return '-';
        if (time < 1000) {
            return time + 'ms';
        } else {
            return (time / 1000).toFixed(2) + 's';
        }
    }

    /**
     * 截断文本
     */
    truncateText(text, maxLength) {
        if (!text) return '-';
        if (text.length > maxLength) {
            return text.substring(0, maxLength) + '...';
        }
        return text;
    }

    /**
     * 渲染分页
     */
    renderPagination(pageData) {
        const paginationInfo = document.getElementById('pagination-info');
        const paginationControls = document.getElementById('pagination-controls');
        const totalPages = pageData.totalPages || 1;
        const currentPage = pageData.currentPage || 1;
        const totalSize = pageData.totalSize || 0;

        // 更新分页信息
        paginationInfo.innerHTML = `共 ${totalSize} 条数据，第 ${currentPage} / ${totalPages} 页`;

        // 移除总页数<=1的判断，确保始终显示分页控件
        let controlsHtml = '';

        // 首页按钮
        controlsHtml += `<button class="btn btn-small" ${currentPage === 1 ? 'disabled' : ''} onclick="operationLogManager.changePage(1)" title="首页">首页</button>`;

        // 上一页按钮
        controlsHtml += `<button class="btn btn-small" ${currentPage === 1 ? 'disabled' : ''} onclick="operationLogManager.changePage(${currentPage - 1})">上一页</button>`;

        // 页码按钮
        const startPage = Math.max(1, currentPage - 2);
        const endPage = Math.min(totalPages, currentPage + 2);

        for (let i = startPage; i <= endPage; i++) {
            const activeClass = i === currentPage ? 'btn-primary' : '';
            controlsHtml += `<button class="btn btn-small ${activeClass}" onclick="operationLogManager.changePage(${i})"><span>${i}</span></button>`;
        }

        // 显示省略号和末页
        if (endPage < totalPages) {
            if (endPage < totalPages - 1) {
                controlsHtml += `<span class="pagination-ellipsis">...</span>`;
            }
            controlsHtml += `<button class="btn btn-small" onclick="operationLogManager.changePage(${totalPages})"><span>${totalPages}</span></button>`;
        }

        // 下一页按钮
        controlsHtml += `<button class="btn btn-small" ${currentPage === totalPages ? 'disabled' : ''} onclick="operationLogManager.changePage(${currentPage + 1})">下一页</button>`;

        // 末页按钮
        controlsHtml += `<button class="btn btn-small" ${currentPage === totalPages ? 'disabled' : ''} onclick="operationLogManager.changePage(${totalPages})" title="末页">末页</button>`;

        paginationControls.innerHTML = controlsHtml;
    }

    /**
     * 切换页面
     */
    changePage(page) {
        this.currentPage = page;
        this.loadLogList();
    }

    /**
     * 切换页面大小
     */
    changePageSize(size) {
        this.pageSize = parseInt(size);
        this.currentPage = 1; // 重置到第一页
        this.loadLogList();
    }

    /**
     * 显示详情
     */
    async showDetail(logId) {
        try {
            const api = await getApiInstanceWithRetry();
            if (!api) {
                throw new Error('API服务不可用');
            }

            // 使用api.js中的方法
            const result = await api.getOperationLogDetail(logId);

            if (result.code === 0 && result.data) {
                this.renderDetail(result.data);
                this.showModal();
            } else {
                throw new Error(result.msg || '未找到日志详情');
            }
        } catch (error) {
            console.error('加载日志详情失败:', error);
            alert('加载日志详情失败: ' + error.message);
        }
    }

    /**
     * 渲染详情内容
     */
    renderDetail(log) {
        const modalBody = document.getElementById('modalBody');

        modalBody.innerHTML = `
            <div class="detail-grid">
                <div class="detail-item">
                    <div class="detail-label">操作时间</div>
                    <div class="detail-value">${this.formatDateTime(log.operationTime)}</div>
                </div>
                <div class="detail-item">
                    <div class="detail-label">链路追踪ID</div>
                    <div class="detail-value">${log.traceId || '-'}</div>
                </div>
                <div class="detail-item">
                    <div class="detail-label">模块类型</div>
                    <div class="detail-value">${this.formatModuleType(log.moduleType)}</div>
                </div>
                <div class="detail-item">
                    <div class="detail-label">操作类型</div>
                    <div class="detail-value">${log.operationType}</div>
                </div>
                <div class="detail-item">
                    <div class="detail-label">业务ID</div>
                    <div class="detail-value">${log.businessId || '-'}</div>
                </div>
                <div class="detail-item">
                    <div class="detail-label">业务名称</div>
                    <div class="detail-value">${log.businessName || '-'}</div>
                </div>
                <div class="detail-item">
                    <div class="detail-label">操作人</div>
                    <div class="detail-value">${log.operator || '-'}</div>
                </div>
                <div class="detail-item">
                    <div class="detail-label">执行耗时</div>
                    <div class="detail-value">${this.formatExecutionTime(log.executionTime)}</div>
                </div>
                <div class="detail-item">
                    <div class="detail-label">请求方法</div>
                    <div class="detail-value">${log.requestMethod || '-'}</div>
                </div>
                <div class="detail-item">
                    <div class="detail-label">请求URL</div>
                    <div class="detail-value" title="${log.requestUrl || '-'}">${this.truncateText(log.requestUrl || '-', 50)}</div>
                </div>
                <div class="detail-item">
                    <div class="detail-label">请求IP</div>
                    <div class="detail-value">${log.requestIp || '-'}</div>
                </div>
                <div class="detail-item">
                    <div class="detail-label">操作状态</div>
                    <div class="detail-value">${this.formatStatus(log.status)}</div>
                </div>
            </div>
            
            ${log.operationDescription ? `
                <div style="margin-bottom: 15px;">
                    <div class="detail-label">操作描述</div>
                    <div class="json-container">
                        <pre>${log.operationDescription}</pre>
                    </div>
                </div>
            ` : ''}
            
            ${log.requestParams ? `
                <div style="margin-bottom: 15px;">
                    <div class="detail-label">请求参数</div>
                    <div class="json-container">
                        <pre>${this.formatJson(log.requestParams)}</pre>
                    </div>
                </div>
            ` : ''}
            
            ${log.responseResult ? `
                <div style="margin-bottom: 15px;">
                    <div class="detail-label" style="color: #409eff; font-weight: bold;">响应结果</div>
                    <div class="json-container" style="border-left: 4px solid #409eff;">
                        <pre>${this.formatJson(log.responseResult)}</pre>
                    </div>
                </div>
            ` : '<div style="margin-bottom: 15px;"><div class="detail-label" style="color: #909399;">响应结果</div><div style="color: #c0c4cc; font-style: italic;">无数据</div></div>'}
            
            ${log.beforeData ? `
                <div style="margin-bottom: 15px;">
                    <div class="detail-label" style="color: #e6a23c; font-weight: bold;">操作前数据</div>
                    <div class="json-container" style="border-left: 4px solid #e6a23c;">
                        <pre>${this.formatJson(log.beforeData)}</pre>
                    </div>
                </div>
            ` : '<div style="margin-bottom: 15px;"><div class="detail-label" style="color: #909399;">操作前数据</div><div style="color: #c0c4cc; font-style: italic;">无数据</div></div>'}
            
            ${log.afterData ? `
                <div style="margin-bottom: 15px;">
                    <div class="detail-label" style="color: #67c23a; font-weight: bold;">操作后数据</div>
                    <div class="json-container" style="border-left: 4px solid #67c23a;">
                        <pre>${this.formatJson(log.afterData)}</pre>
                    </div>
                </div>
            ` : '<div style="margin-bottom: 15px;"><div class="detail-label" style="color: #909399;">操作后数据</div><div style="color: #c0c4cc; font-style: italic;">无数据</div></div>'}
            
            ${log.changedFields ? `
                <div style="margin-bottom: 15px;">
                    <div class="detail-label" style="color: #409eff; font-weight: bold;">变更字段</div>
                    <div class="json-container" style="border-left: 4px solid #409eff;">
                        <pre>${this.formatJson(log.changedFields)}</pre>
                    </div>
                </div>
            ` : ''}
            
            ${log.errorMessage ? `
                <div style="margin-bottom: 15px;">
                    <div class="detail-label" style="color: #f56c6c; font-weight: bold;">错误信息</div>
                    <div class="json-container" style="background: #fef0f0; border: 1px solid #fbc4c4; border-left: 4px solid #f56c6c;">
                        <pre style="color: #f56c6c;">${log.errorMessage}</pre>
                    </div>
                </div>
            ` : ''}
        `;
    }

    /**
     * 格式化JSON
     */
    formatJson(jsonStr) {
        if (!jsonStr) return '';
        try {
            const parsed = JSON.parse(jsonStr);
            return JSON.stringify(parsed, null, 2);
        } catch (e) {
            return jsonStr;
        }
    }

    /**
     * 显示弹窗
     */
    showModal() {
        document.getElementById('detailModal').style.display = 'block';
        document.body.style.overflow = 'hidden';
    }

    /**
     * 关闭弹窗
     */
    closeModal() {
        document.getElementById('detailModal').style.display = 'none';
        document.body.style.overflow = 'auto';
    }
}

// 导出到全局，供其他模块使用
window.OperationLogManager = OperationLogManager;
